#include "get_song_info.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFLEN_SONGID 16
#define BUFLEN_URL 255
#define BUFLEN_PATH 255

FILE *fp;
CURL *curl;
char strid[BUFLEN_SONGID];

size_t write_data_cstr(void *ptr, size_t size, size_t nmemb, void *stream);
size_t write_data_file(void *ptr, size_t size, size_t nmemb, void *stream);

void getnet_set_songid(long long int songid)
{
    char strurl[BUFLEN_URL] = "http://music.163.com/api/song/detail/?id=";
    snprintf(strid, BUFLEN_SONGID, "%lld", songid);
    strcat(strurl, strid);
    strcat(strurl, "&ids=%5B");
    strcat(strurl, strid);
    strcat(strurl, "%5D");
    curl_easy_setopt(curl, CURLOPT_URL, strurl);
}

char *getnet_get_songinfo()
{
    char buf[MAXBUFLEN];
    // CURLOPT_WRITEFUNCTION
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_cstr);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, buf);
    curl_easy_perform(curl);
    char *res = malloc(strlen(buf) + 1);
    strcpy(res, buf);
    return res;
}

int getnet_get_cover_file(char *coverurl)
{
    char strpath[BUFLEN_PATH] = "./";
    strcat(strpath, strid);
    if (strstr(coverurl, ".jpg"))
        strcat(strpath, ".jpg");
    if (strstr(coverurl, ".png"))
        strcat(strpath, ".png");
    if ((fp = fopen(strpath, "w")) == NULL)
    {
        curl_easy_cleanup(curl);
        return -1;
    }
    // CURLOPT_WRITEFUNCTION
    curl_easy_setopt(curl, CURLOPT_URL, coverurl);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_file);
    curl_easy_perform(curl);
    return 0;
}

int getnet_get_songinfo_file()
{
    char strpath[BUFLEN_PATH] = "./";
    strcat(strpath, strid);
    strcat(strpath, ".json");
    if ((fp = fopen(strpath, "w")) == NULL)
    {
        curl_easy_cleanup(curl);
        return -1;
    }
    // CURLOPT_WRITEFUNCTION
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_file);
    curl_easy_perform(curl);
    return 0;
}

void init_curl()
{
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
}

void end_curl()
{
    curl_easy_cleanup(curl);
}

void reset_curl()
{
    end_curl();
    init_curl();
}

size_t write_data_cstr(void *ptr, size_t size, size_t nmemb, void *stream)
{
    if (strlen((char *)stream) + strlen((char *)ptr) > MAXBUFLEN)
        return 0;
    strcat(stream, (char *)ptr);
    return size * nmemb;
}

size_t write_data_file(void *ptr, size_t size, size_t nmemb, void *stream)
{
    int written = fwrite(ptr, size, nmemb, (FILE *)fp);
    return written;
}